package com.example.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.generator.IFill;
import com.example.sys.entity.Menu;
import com.example.sys.mapper.MenuMapper;
import com.example.sys.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuage
 * @since 2023-12-20
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Override
    public List<Menu> getAllMenu() {
//        一级菜单
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",0);
        List<Menu> menuList = this.list(wrapper);
        //        填充子菜单
        setMenuChildren(menuList);
        return menuList;
    }

    private void  setMenuChildren(List<Menu> menuList){
        if (menuList !=null){
            for (Menu menu:menuList){
                QueryWrapper<Menu> subwrapper = new QueryWrapper<>();
                subwrapper.eq("parent_id",menu.getMenuId());
                List<Menu> submenuList = this.list(subwrapper);
                menu.setChildren(submenuList);
//                递归
                setMenuChildren(submenuList);
            }
        }
    }

    @Override
    public List<Menu> getMenuListByUerId(Integer userId) {
//        一级菜单
         List<Menu> menuList = this.baseMapper.getMenuListByUerId(userId, 0);
//        子菜单
        setMenuChildrenByUserID(userId,menuList);
        return menuList;
    }

    private void  setMenuChildrenByUserID(Integer userId,List<Menu> menuList){
        if (menuList != null){
            for(Menu menu:menuList){
                List<Menu> subMenuList = this.baseMapper.getMenuListByUerId(userId, menu.getMenuId());
                menu.setChildren(subMenuList);
//                递归
                setMenuChildrenByUserID(userId,subMenuList);
            }
        }
    }
}



